package me.ivps.android.weibo.othercomponent;

import me.ivps.android.weibo.R;
import me.ivps.android.weibo.support.settinghelper.SettingUtility;
import me.ivps.android.weibo.support.utils.GlobalContext;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * 新消息提醒
 * 
 * User: qii Date: 12-9-14
 */
public class AppNewMsgAlarm {
    
    private static final int REQUEST_CODE = 195;
    
    /**
     * 开始循环提醒
     * 
     * @param context
     * @param silent
     */
    public static void startAlarm(Context context, boolean silent) {
        String value = SettingUtility.getFrequency();
        
        long time = AlarmManager.INTERVAL_DAY;
        if (value.equals("1")) {
            time = (3 * 60 * 1000);
        }
        if (value.equals("2")) {
            time = (AlarmManager.INTERVAL_FIFTEEN_MINUTES);
        }
        if (value.equals("3")) {
            time = (AlarmManager.INTERVAL_HALF_HOUR);
        }
        
        AlarmManager alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, FetchNewMsgService.class);
        PendingIntent sender = PendingIntent.getService(context, REQUEST_CODE,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, time,
                sender);
        if (!silent) {
            Toast.makeText(context,
                    context.getString(R.string.start_fetch_msg),
                    Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 停止循环提醒
     * 
     * @param context
     * @param clearNotification
     */
    public static void stopAlarm(Context context, boolean clearNotification) {
        AlarmManager alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, FetchNewMsgService.class);
        PendingIntent sender = PendingIntent.getService(context, REQUEST_CODE,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarm.cancel(sender);
        if (clearNotification) {
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(Long.valueOf(
                    GlobalContext.getInstance().getCurrentAccountId())
                    .intValue());
        }
    }
}
